package com.zhkj.crawl.rank.ext;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverLogLevel;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

@Slf4j
public class ChromeAliExt2 {
    private static final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");

    public static void main(String[] args) {
        enter();

    }

    private static void enter(){
        ChromeDriver driver = initDriver();
        try {
            String loginUrl = "https://global.alipay.com/ilogin/account_login.htm?_route=QK";
            toPage(driver, loginUrl);

            optLogin(driver);
        }finally {
            //driver.quit();
        }

    }

    private static void optLogin(ChromeDriver driver) {
        sleep(2);
        // 填写账密
        WebElement username = driver.findElementById("login_id");
        WebElement password = driver.findElementById("password");

        username.sendKeys("wcl93099@gmail.com");
        password.sendKeys("chrisWin,,");

        sleep(1);
        driver.findElementByCssSelector("button.ant-btn-lg").click();

    }


    private static void toPage(ChromeDriver driver, String url){
        driver.get(url);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    private static ChromeDriver initDriver() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setLogLevel(ChromeDriverLogLevel.OFF);
        if(!isWindows){
            chromeOptions.addArguments("-headless");
        }
        chromeOptions.addArguments("--silent");
        chromeOptions.addArguments("log-level=3");
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("source", " Object.defineProperty(navigator, 'webdriver', {\n" +
                "      get: () => undefined\n" +
                "    })");
        chromeDriver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument", parameters);

        return chromeDriver;
    }


    private static void sleep(Integer second){
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void screenshot(ChromeDriver driver) {
        //调用截图方法 ,指定了OutputType.FILE做为参数传递给getScreenshotAs()方法，其含义是将截取的屏幕以文件形式返回
        if(!isWindows){
            File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            String name = "selenium-" + RandomStringUtils.randomAlphanumeric(6) + ".jpg";
            try {
                FileUtils.copyFile(srcFile, new File("D:\\" + name + ""));
            } catch (IOException e) {
                log.error("截图错误", e);
            }
        }
    }


    static {
        Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
        Logger.getLogger("org.asynchttpclient.netty").setLevel(Level.OFF);

        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        if (isWindows) {
            System.setProperty("webdriver.chrome.driver", "D:\\Program Files\\chromedriver_91_0_4472_101.exe");
        }
    }

    private static final Logger[] pin;
    static {
        pin = new Logger[]{
                Logger.getLogger("com.asynchttpclient.netty"),
                Logger.getLogger("org.apache.commons.httpclient"),
                Logger.getLogger("org.openqa.selenium")
        };

        for (Logger l : pin) {
            l.setLevel(Level.OFF);
        }
    }
}
